package com.dmall.graph.dfs.app;

import com.dmall.graph.Graph;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class SingleSourcePath {
    private Graph G;
    private boolean[] visited;
    private int[] pre;
    private int s;

    public SingleSourcePath(Graph G, int s) {
        this.G = G;
        this.s = s;
        this.visited = new boolean[G.V()];
        this.pre = new int[G.V()];
        Arrays.fill(this.pre, -1);

        dfs(s, s);
    }

    private void dfs(int v, int p) {
        visited[v] = true;
        pre[v] = p;
        for (Integer w : G.adj(v)) {
            if (!visited[w]) {
                dfs(w, v);
            }
        }
    }

    public boolean isCollectedTo(int t) {
        G.validateVertex(t);
        return visited[t];
    }

    public Iterable<Integer> path(int t) {
        ArrayList<Integer> res = new ArrayList<>();
        if (!isCollectedTo(t)) {
            return res;
        }

        int cur = t;
        while (cur != s) {
            res.add(cur);
            cur = pre[cur];
        }
        res.add(s);
        Collections.reverse(res);
        return res;
    }

    public static void main(String[] args) {
        String filePath = SingleSourcePath.class.getClassLoader().getResource("g.txt").getPath();
        Graph graph = new Graph(filePath);
        SingleSourcePath singleSourcePath = new SingleSourcePath(graph, 0);
        System.out.println(singleSourcePath.isCollectedTo(6));
        System.out.println(singleSourcePath.isCollectedTo(5));
        System.out.println(singleSourcePath.path(6));
        System.out.println(singleSourcePath.path(5));
    }
}
